import CONST from '@/utils/Const';
import store from '@/store';
import Storage from '@/utils/Storage';
import api from '@/api/permission.controller';
import Tools from '@/utils/Tools';
import { asyncRoutes } from '@/router';
export default {
	namespaced : true,
	state : {
		treeList : [], // 左侧菜单
		isCollapse : false
	},
	getters : {
		treeList : state => {
			return state.treeList;
		},
		collapse : state => {
			return state.isCollapse;
		}
	},
	mutations : {
		[CONST.TREE_LIST] (state, data) {
			state.treeList = data;
			Storage.set(CONST.TREE_LIST, data, 1);
		},
		[CONST.RESET_TREE_LIST] (state) {
			state.treeList = [];
			Storage.set(CONST.TREE_LIST, [], 1);
		},
		[CONST.COLLAPSE] (state) {
			state.isCollapse = !state.isCollapse;
		}
	},
	actions : {
		async treeAction ({ commit }) {
			try {
				const {userId} = Storage.get(CONST.USER,1);
				let list = await api.getMenu(userId);
				// 按钮权限
				store.commit('Permissions/' + CONST.PERMISSIONS, list.data.points);
				// 路由转map对象
				const routesMap = Tools.routesToMap(asyncRoutes);
				// 接口路由映射
				const routeList = Tools.mappingRoutes(list.data.menu, routesMap);
				return new Promise(resolve => {
					commit(CONST.TREE_LIST, routeList);
					// 单独处理首页
					const routes = [...routeList];
					routes[0] = asyncRoutes[0];
					resolve(routes);
				});
			} catch (error) {
				console.log(error);
			}
		},
		collapseAction ({ commit }, item) {
			commit(CONST.COLLAPSE, item);
		},
		resetTreeListAction ({ commit }) {
			commit(CONST.RESET_TREE_LIST);
		}
	}
};

